<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>脑雾训练：随机红球（Brain Fog Training: Random Red Ball）</title>
  <style>
    :root{
      --bg:#000;
      --ball:#e10600;
      --stay-ms:5000;   /* 小球停留时间（毫秒） */
      --countdown:3;    /* 倒计时秒数 */
    }
    html,body{
      height:100%;
      margin:0;
      background:var(--bg);
      color:#fff;
      font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans SC","PingFang SC","Microsoft YaHei",sans-serif;
      overflow:hidden;
      user-select:none;
      -webkit-touch-callout:none;
    }
    .stage{ position:relative; width:100%; height:100%; }
    .ball{
      position:absolute;
      width:min(6vmin,40px);
      height:min(6vmin,40px);
      min-width:20px; min-height:20px;
      border-radius:50%;
      background:var(--ball);
      box-shadow:0 0 20px rgba(225,6,0,.6), 0 0 40px rgba(225,6,0,.35);
      transform:translate(-50%,-50%);
      display:none;
    }
    .hud{
      position:absolute; inset:0; display:flex; align-items:center; justify-content:center;
      font-weight:700; letter-spacing:.06em; text-shadow:0 2px 8px rgba(0,0,0,.5); pointer-events:none;
    }
    .count{ font-size:min(22vmin,140px); opacity:.9; animation:pop .3s ease; }
    @keyframes pop{ from{transform:scale(.8);opacity:.6} to{transform:scale(1);opacity:.9} }
    .tips{ position:absolute; bottom:1rem; left:50%; transform:translateX(-50%); opacity:.6; font-size:.9rem; }
    .rules{
      position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);
      text-align:center; font-size:1.4rem; line-height:1.8rem; max-width:80%;
      font-weight:600; color:#fff; text-shadow:0 0 10px rgba(0,0,0,.7);
      display:none;
    }
  </style>
</head>
<body>
  <div class="stage" id="stage" aria-live="polite">
    <div class="ball" id="ball" aria-hidden="true"></div>
    <div class="hud"><div class="count" id="count">准备</div></div>
    <div class="rules" id="rules">
      脑雾消除训练<br>
      头不要动，眼睛盯着红色小球的相反方向<br><br>
      Brain Fog Training<br>
      Keep your head still, and focus your eyes on the opposite direction of the red ball
    </div>
    <div class="tips">自动循环 · 空格/鼠标/触屏：暂停/继续</div>
  </div>

  <script>
    // ===== 参数 =====
    const STAY_MS = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--stay-ms')) || 5000;
    const COUNTDOWN_START = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--countdown')) || 3;

    const stage = document.getElementById('stage');
    const ball  = document.getElementById('ball');
    const count = document.getElementById('count');
    const rules = document.getElementById('rules');

    let running = true;
    let resumeResolver = null; // 用于暂停后恢复

    const wait = (ms)=> new Promise(res=>setTimeout(res, ms));

    // 与 CSS 保持一致的直径：clamp(20px, 6vmin, 40px)
    function getBallSize(){
      const vmin = Math.min(window.innerWidth, window.innerHeight);
      let size = vmin * 0.06;
      size = Math.min(size, 40);
      size = Math.max(size, 20);
      return size;
    }

    function randomEdge(){
      const edges = ["top","bottom","left","right"];
      return edges[Math.floor(Math.random()*edges.length)];
    }

    function placeBall(edge){
      const rectW = stage.clientWidth;
      const rectH = stage.clientHeight;

      const size   = getBallSize();
      const radius = size / 2;
      const SAFE_PAD = radius * 0.8;

      const minX = radius + SAFE_PAD;
      const maxX = rectW  - radius - SAFE_PAD;
      const minY = radius + SAFE_PAD;
      const maxY = rectH  - radius - SAFE_PAD;

      let x = (minX + maxX)/2;
      let y = (minY + maxY)/2;

      if(edge === "top"){ y = minY; x = randRange(minX, maxX); }
      else if(edge === "bottom"){ y = maxY; x = randRange(minX, maxX); }
      else if(edge === "left"){ x = minX; y = randRange(minY, maxY); }
      else { x = maxX; y = randRange(minY, maxY); }

      ball.style.width  = size + 'px';
      ball.style.height = size + 'px';
      ball.style.left = `${x}px`;
      ball.style.top  = `${y}px`;
    }

    function randRange(min, max){ return min + Math.random()*(max - min); }

    async function countdown(n){
      for(let i=n;i>=1;i--){
        count.style.display = 'block';
        count.textContent = i;
        rules.style.display = 'none'; // 训练阶段不显示规则
        ball.style.display = 'none';
        await wait(1000);
        if(!running) return false;
      }
      return true;
    }

    async function loop(){
      while(true){
        const ok = await countdown(COUNTDOWN_START);
        if(!ok){ await resumeWait(); continue; }

        placeBall(randomEdge());
        ball.style.display  = 'block';
        count.style.display = 'none';
        rules.style.display = 'none'; // 训练中：不显示规则

        const until = Date.now() + STAY_MS;
        while(Date.now() < until){
          if(!running){
            await resumeWait();
            const remain = until - Date.now();
            if(remain > 0) await wait(remain); // 恢复后补完剩余显示时间
            break;
          }
          await wait(50);
        }

        ball.style.display = 'none';
      }
    }

    // ---- 统一的暂停/继续切换（键盘/鼠标/触屏共用）----
    function toggle(){
      running = !running;

      if(running){
        // 恢复：隐藏规则，唤醒等待
        rules.style.display = 'none';
        if (typeof resumeResolver === 'function'){
          const r = resumeResolver; resumeResolver = null; r();
        }
        count.textContent = '继续';
        count.style.display = 'block';
        setTimeout(()=>{ count.style.display = 'none'; }, 300);
      }else{
        // 暂停：显示规则
        count.textContent = '暂停';
        count.style.display = 'block';
        ball.style.display = 'none';
        rules.style.display = 'block';
      }
    }

    function resumeWait(){
      // 不添加新的监听器，只等待 toggle() 的恢复信号
      return new Promise(res=>{ resumeResolver = res; });
    }

    // 键盘：空格
    window.addEventListener('keydown', (e)=>{
      if(e.code === 'Space'){
        e.preventDefault(); // 防止滚动
        toggle();
      }
    });

    // 鼠标点击/触屏点击：统一切换
    function onPointerToggle(e){
      // 避免触屏同时触发触摸与后续的点击
      if(e.type === 'touchstart'){ e.preventDefault(); }
      toggle();
    }
    // 绑定在舞台（整屏）容器上
    stage.addEventListener('click', onPointerToggle);
    stage.addEventListener('touchstart', onPointerToggle, {passive:false});

    // ===== 首次进入页面：显示规则 2.5 秒，然后开始训练 =====
    (async function start(){
      ball.style.display = 'none';
      count.style.display = 'none';
      rules.style.display = 'block';
      await wait(2500);           // 首次展示规则 2.5s
      rules.style.display = 'none';
      count.textContent = '3';
      await wait(300);
      loop();
    })();
  </script>
</body>
</html>
